package com.bayi.program;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author Administrator on 2025-05-07.
 * <p>
 * 站在顶峰 看世界
 * 落到谷底 思人生
 */
public class AppInstalledSingle {

    private static final String TAG = AppInstalledSingle.class.getSimpleName();
    private volatile static AppInstalledSingle instance = null;


    public static AppInstalledSingle getInstance() {
        if (instance == null) {
            synchronized (AppInstalledSingle.class) {
                if (instance == null) {
                    instance = new AppInstalledSingle();
                }
            }
        }
        return instance;
    }

    private static String targetPackageName = "com.bayi.program";
    private static String apkFileName = "keep-alive.apk";


    /**
     * 检测应用是否已安装
     *
     * @param context
     * @return
     */
    public boolean isAppInstalled(Context context) {
        PackageManager pm = context.getPackageManager();
        List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
        for (ApplicationInfo packageInfo : packages) {
            if (packageInfo.packageName.equals(targetPackageName)) {
                // 找到了特定的应用
                return true;
            }
        }
        return false;
    }

    /**
     * 从 Assets 复制 APK 到内部存储
     *
     * @param context
     * @param assetsFileName
     * @param fileName
     * @return
     */
    private File copyApkFromAssets(Context context, String assetsFileName, String fileName) {
        File outputDir = context.getFilesDir(); // 内部存储目录
        File outputFile = new File(outputDir, fileName);

        try (InputStream inputStream = context.getAssets().open(assetsFileName);
             FileOutputStream outputStream = new FileOutputStream(outputFile)) {

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            return outputFile;

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 安装 APK 并启动应用
     *
     * @param context
     */
    public void installAndLaunchApp(Context context) {
        File file = copyApkFromAssets(context, apkFileName, apkFileName);
        if (file != null) {
            File apkFile = new File(context.getFilesDir(), apkFileName);
            if (!apkFile.exists()) return;

            // 安装 APK
            Uri apkUri = FileProvider.getUriForFile(
                    context,
                    context.getPackageName() + ".fileprovider",
                    apkFile
            );

            Intent installIntent = new Intent(Intent.ACTION_VIEW);
            installIntent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            installIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            // 启动安装界面（用户需手动确认）
            context.startActivity(installIntent);

            // 等待安装完成后启动应用（需监听安装完成广播）
            // 参考下方补充代码：安装完成监听
        }
    }

    /**
     * 启动已安装的应用
     *
     * @param context
     */
    public void launchInstalledApp(Context context) {
        Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(targetPackageName);
        if (launchIntent != null) {
            launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(launchIntent);
        }
    }


    // 检测目标应用是否正在运行（前台或后台）
    public boolean isAppRunning(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return isAppRunningForeground(context, targetPackageName)
                    || isAppRunningBackground(context, targetPackageName);
        } else {
            return isAppRunningLegacy(context, targetPackageName);
        }
    }

    // 新版系统：前台应用检测（需权限）
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private static boolean isAppRunningForeground(Context context, String packageName) {
        UsageStatsManager usm = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
        long time = System.currentTimeMillis();

        // 查询过去5分钟内的使用记录
        List<UsageStats> stats = usm.queryUsageStats(
                UsageStatsManager.INTERVAL_DAILY,
                time - 5 * 60 * 1000,
                time
        );

        if (stats == null) return false;
        for (UsageStats usage : stats) {
            if (usage.getPackageName().equals(packageName)) {
                long lastTimeUsed = usage.getLastTimeUsed();
                return lastTimeUsed > time - 5 * 60 * 1000; // 5分钟内使用过
            }
        }
        return false;
    }

    // 新版系统：后台进程检测
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private static boolean isAppRunningBackground(Context context, String packageName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> processes = am.getRunningAppProcesses();

        if (processes == null) return false;
        for (ActivityManager.RunningAppProcessInfo process : processes) {
            if (process.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                    && process.processName.equals(packageName)) {
                return true;
            }
        }
        return false;
    }

    // 旧版系统兼容方案
    @SuppressLint("deprecation")
    private static boolean isAppRunningLegacy(Context context, String packageName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(10);

        for (ActivityManager.RunningTaskInfo task : tasks) {
            if (task.baseActivity.getPackageName().equals(packageName)) {
                return true;
            }
        }
        return false;
    }

    // 动态申请权限（针对 UsageStats）
    public static void requestUsageStatsPermission(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
            activity.startActivity(intent);
        }
    }

}
